﻿namespace Homework04
{
    internal class Program
    {
        /// <summary>
        /// 用户输入一个二进制数，给出它的十进制形式
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            //To get the input from users
            Console.Write("Please enter a binary number:");
            //Read the input from the user
            string? binaryInput = Console.ReadLine();
            int decimalNumber = 0;
            // Get the length of the binary string to determine the position of each bit
            int length = binaryInput.Length;
            // Loop through each character in the binary string from the end to the start
            foreach (char c in binaryInput)
            {
                if (c != '0' && c != '1')
                {
                    Console.WriteLine("Input error!Please entre a valid binary number!");
                    return;
                }
            }
            for (int i = length - 1; i >= 0; i--)
            {
                // Convert the current character to an integer (0 or 1).
                int bitValue = binaryInput[i] - '0';
                // Calculate the decimal value of this bit by raising 2 to the power of its position index.
                decimalNumber += bitValue * (int)Math.Pow(2, length - 1 - i);
            }
            // Output the decimal representation of the binary number
            Console.WriteLine($"Decimal form:{decimalNumber}");
        }
    }
}
